package com.hy.dao;

import com.hy.entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * date:2020/12/22
 * description:dao类，使用jdbcTemplate去操作数据库
 * Author:gxh
 */
@Repository
public class EmpDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Emp selectEmpById(int id){

        String sql = "select id,name,salary from emp where id= ? ";

        Emp emp = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(Emp.class), id);

        return emp;

    }

    public List<Emp> selectEmps(){

        String sql = "select id,name,salary from emp ";
//        query:返回的是个集合  第二个参数表示集合里面元素的类型
        List<Emp> emps = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Emp.class));
        return emps;
    }

    public List selectEmpsByList(){
        String sql = "select id,name,salary from emp ";
//        query:返回的是个集合  第二个参数表示集合里面元素的类型
        List<Map<String, Object>> emps = jdbcTemplate.queryForList(sql);
        return emps;
    }


    public int updateById(String newName){

        String sql = "update emp set name=? where id=1";
        int update = jdbcTemplate.update(sql, newName);
        return update;

    }

    public int deleteById(int id){

        String sql = "delete from emp where id=? ";
        int result = jdbcTemplate.update(sql, id);
        return result;

    }

    public int addEmp(Emp emp){

        String sql = "insert into emp (id,name,salary) values(?,?,?) ";
        int result = jdbcTemplate.update(sql,emp.getId(),emp.getName(),emp.getSalary());
        return result;

    }

}
